import Taro from '@tarojs/taro';

import { defaultPageSize } from '../config'
import { any } from 'prop-types';
import { User as UserUtils } from '../utils/user'
import { Utils } from '../utils/utils'
import { default as ApplyUtils } from '../utils/apply'

import ApplyService from '../services/apply'
import CollectionService from '../services/collect'
import CreditService from '../services/credit'
import LocationService from '../services/location'

const userUtils = new UserUtils()
const utils = new Utils()
const applyService = new ApplyService()
const applyUtils = new ApplyUtils()
const collectionService = new CollectionService()
const creditService = new CreditService()
const locationService = new LocationService()

type UserLocation = {
  city: string,   // 用户选择的城市
}

const userLocation: UserLocation = {
  city: '全国',
}

export default {
  namespace: 'common',
  state: {
    defaultPageSize,     // 默认分页数
    userLocation: userUtils.getUserLocationFromStorage(),      // 用户位置
    userApplyList: applyUtils.getOrderFromLocalStorage(),      // 用户已申请订单列表
    userCollectionList: userUtils.getCollectionFromLocalStorage(),   // 用户已收藏的产品列表
    userCredit: {},      // 用户信用数据
    activeTabIndex: 0,   // 贷款商城页tab下标，0:快速 1:银行  默认选中快速产品
    isLoginAlready: userUtils.isLogin(),  // 用户是否已登录
    isLoginValid: userUtils.isLoginValid(),   // 用户登录是否已过期
    userInfo: userUtils.getUserFromLocalStorage(),    // 已登录的用户信息
    codeTimerCount: 60,     // 短信验证码发送间隔(秒)
    regions: utils.getInitRegionsById()   // 省市区数组，用于城市选择框
  },

  effects: {
    // 刷新用户申请
    * refreshUserApplyList({ payload }, { call, put, select }) {

      // 查询所有订单
      const { code, data } = yield call(applyService.getMyOrder.bind(applyService), 1, 1000)

      if (code === 0) {
        // 保存到缓存
        applyUtils.saveOrderToLocalStorage(data.data)

        // 更新申请列表
        yield put({
          type: 'save', payload: {
            userApplyList: data.data
          }
        });
      }

    },

    // 刷新用户收藏
    * refreshUserCollectionList({ payload }, { call, put, select }) {
      // 查询所有收藏
      const { code, data } = yield call(collectionService.getCollection.bind(collectionService), 1, 1000)

      // 特殊处理，这个接口没有返回code,我也不知为什么
      // if (code === 0) {
      if (data) {
        // 保存到缓存
        userUtils.saveCollectionToLocalStorage(data)

        // 更新收藏列表
        yield put({
          type: 'save', payload: {
            userCollectionList: data
          }
        });
      }
    },

    // 查询用户信用
    * getUserCredit({ payload }, { call, put, select }) {
      // 查询用户信用
      const { code, data } = yield call(creditService.getUserCredit.bind(creditService))

      if (code === 0) {
        // 更新用户信用
        yield put({
          type: 'save', payload: {
            userCredit: data
          }
        });

        // 调用回调函数
        if (payload.callback) {
          payload.callback.call(null, data)
        }
      }
    },

    // 更新用户信用
    * updateUserCredit({ payload }, { call, put, select }) {
      const { credit } = payload
      // 更新用户信用
      yield call(creditService.updateUserCredit.bind(creditService), credit)
    },

    // 刷新用户位置信息
    * refreshUserLocation({ payload }, { call, put, select }) {
      // 1. 根据ip查询位置(经纬度)
      const { result } = yield call(locationService.getUserLocationByIp.bind(locationService))

      if (result) {
        const location = result.location

        // 2. 根据位置查询地点详细信息
        const response = yield call(locationService.getUserLocation.bind(locationService), location.lat, location.lng)
        const detail = response.result
        if (detail) {
          const { ad_info } = detail
          let locationObj = {
            province: ad_info.province,
            city: ad_info.city,
            district: ad_info.district,
            adcode: ad_info.adcode,
            location: ad_info.location
          }

          // 生成用户位置数据对象
          locationObj = locationService.generateLocationObj(locationObj)

          // 更新state
          yield put({
            type: 'save', payload: {
              userLocation: locationObj
            }
          })

          // 保存位置数据到缓存
          userUtils.saveUserLocationToStorage(locationObj)
        }

      }
    }
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },

};
